'use strict';
const Path = require('path');
const fs=require('fs');

const Hapi = require('hapi');
const Joi = require('joi');
const Inert = require('inert');
const Vision = require('vision');
const HapiSwagger = require('hapi-swagger');

const mock = require("./mock.js");
const Options = require('./config/plugins.config.js');
const RouteLoader=require('hapi-auto-route');

const Collector=require('./modules/collector.js');

const Uploader=require('./modules/uploader.js');



const nconf = require('nconf').argv().env().file({ file: 'server.json' });

const UPLOAD_PATH="upload";


const server = new Hapi.Server({
    connections: {
        routes: {
            cors: true,
            files: {
                relativeTo: Path.join(__dirname, '../')
            }
        }
    }
});

server.connection({
    host:nconf.get("SERVER_HOST"),
    port: nconf.get("SERVER_PORT")
});

server.register([
    Inert,
    Vision,
    {
        register: RouteLoader,
        options: {
            dir:__dirname+'/router'
        }
    },
    {
        register: require('good'),
        options: Options.Good
    },
    {
        'register': HapiSwagger,
        'options': Options.HapiSwagger
    }], (err) => {
    if (err) {
        console.error(err)
    } else {
        server.start((err) => {
            if (err) {
                console.log(err);
            } else {
                console.log('服务已经正常启动:', server.info.uri);
                if (!fs.existsSync(UPLOAD_PATH)){
                    console.log('开始创建文件上传目录');
                    fs.mkdirSync(UPLOAD_PATH);
                }
            }
        });
    }
});

server.route({
    method: 'GET',
    path: '/mock/default/{type}',
    config: {
        description: '获取默认的对应类型的数据',
        notes: '返回一个{type}类型默认数据，如：image、person、tree、list、article',
        tags: ['api'],
        validate: {
            params: {
                type: Joi.string()
                    .required()
                    .description('默认数据类型[image、person、tree、list、article]')
            },
            query: {
                len: Joi.number()
                    .description('数据长度、list类型数据才需要配置的字段,默认值:10'),
                level: Joi.number()
                    .description('树型结构的层级配置、tree类型数据才需要配置的字段,默认值:4'),
                size: Joi.string()
                    .description('图片尺寸配置、image类型数据才需要配置的字段,默认值:240*120')
            }
        },
        handler: function (request, reply) {
            var type = request.params.type;
            return reply(mock.defaultData({type, ...request.query}));
        }
    }
});

server.route({
    method: 'POST',
    path: '/mock/tree',
    config: {
        description: '获取一个树结构数据',
        notes: '返回一个树结构数据',
        tags: ['api'],
        validate: {
            query: {
                level: Joi.number().description("树的层级定义、表示有几层数据、默认为：4")
            },
            payload: {
                template: Joi.object().description("树节点数据类型配置")
            }
        },
        handler: function (request, reply) {
            let config = request.payload;
            let level = request.query.level;
            let data = mock.tree(config.template, level);
            return reply(data);
        }
    }
});

server.route({
    method: 'POST',
    path: '/mock/object',
    config: {
        description: '获取一个自定义数据结构的数据',
        tags: ['api'],
        validate: {
            query: {
                len: Joi.number().description("如果配置了非零的值时、则会返回一个数组")
            },
            payload: {
                template: Joi.object().description("数据格式模板配置")
            }
        },
        handler: function (request, reply) {
            let config = request.payload;
            let len = request.query.len;
            let data = null;
            if (len && len > 0) {
                data = [];
                for (var i = 0; i < len; i++) {
                    data.push(mock.object(config.template))
                }
            } else {
                data = mock.object(config.template);
            }
            return reply(data);
        }
    }
});

server.route({
    method:"POST",
    path:"/mock/collect",
    config: {
        description: '数据采集接口',
        tags: ['api'],
        validate: {
            payload: {
                url:Joi.string().required().description("需要的采集网址"),
                area:Joi.string().description("需要的采集的内容区域"),
                tag:Joi.string().description("需要的采集的目标"),
                attr: Joi.array().description("采集的数据格式配置")
            }
        },
        handler: function (request, reply) {
            const config=request.payload;
            Collector.collect(config).then(data=>{
                reply(data);
            });
        }
    }
})

server.route({
    method:"POST",
    path:"/mock/jsonp",
    config: {
        description: 'JSONP接口解析工具',
        tags: ['api'],
        validate: {
            payload: {
                jsonp:Joi.string().required().description("jsonp地址"),
                callback:Joi.string().description("回调函数名称")
            }
        },
        handler: function (request, reply) {
            Collector.jsonp(request.payload)
                .then(data=>{
                    reply(data);
                })
        }
    }
})

server.route({
    method: 'POST',
    path: '/mock/upload',
    config: {
        payload: {
            output: 'stream',
            allow: 'multipart/form-data' // important
        }
    },
    handler: function (request, reply) {
        const data = request.payload;
        const file = data['uploader']; // accept a field call avatar
        Uploader.upload(file,{dest: `${UPLOAD_PATH}/`,server:server.info.uri }).then(data=>{
            reply(data)
        })
    }
})

